package bin_tree.leetcode;

/**
 * 对称二叉树
 * @author yuisama
 * @date 2022/02/20 16:32
 **/
public class Num101_SymmetricTree {
    public boolean isSymmetric(TreeNode root) {
        // 边界
        if (root == null) {
            return true;
        }
        return isMirror(root.left,root.right);
    }

    /**
     * 判断left和right这两棵树是否是一个镜像相等
     * @param left
     * @param right
     * @return
     */
    private boolean isMirror(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        }
        if (left == null || right == null) {
            return false;
        }
        if (left.val != right.val) {
            return false;
        }
        // left的左树要和right的右树镜像相等 && left的右树要和right的左树镜像相等
        return isSameTree(left.left,right.right) && isSameTree(left.right,right.left);
    }

    public boolean isSameTree(TreeNode p, TreeNode q) {
        // 边界条件
        if (p == null && q == null) {
            // 两棵树都是空树
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return p.val == q.val &&
                isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}